<template>
  <div class="main_box">
    <el-row class="header-row">
      <el-col>
        <div class="search_wrap">
          <el-form :inline="true" :model="searchForm" ref="searchForm">
            <el-form-item prop="departName">
              <el-input v-model="searchForm.departName" :clearable="true" placeholder="公司名称"></el-input>
            </el-form-item>
            <el-form-item prop="departId">
              <el-select v-model="searchForm.departId" :clearable="true" placeholder="请选择上级公司">
                <el-option v-for="item in departs" :key="item.departId" :label="item.departName" :value="item.departId"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="onSearch">查询</el-button>
              <el-button icon="el-icon-refresh-left" @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col>
        <div class="opration_wrap">
          <el-tooltip content="刷新" placement="top">
            <el-button circle icon="el-icon-refresh-right" @click="reload" size="mini"></el-button>
          </el-tooltip>
          <el-button type="primary" plain icon="fa fa-plus" v-has="permissionAdd" @click="handleClickAdd()" size="mini"> 新增</el-button>
        </div>
      </el-col>
    </el-row>
    <el-row ref="tableRow">
      <el-table :data="tableList" :fit="true" default-expand-all :tree-props="{ children: 'childrens', hasChildren: 'hasChildren' }" row-key="departId">
        <el-table-column prop="departName" label="公司名称"></el-table-column>
        <el-table-column prop="managerUserName" label="公司负责人"></el-table-column>
        <el-table-column prop="parentDepartName" label="上级公司"></el-table-column>
        <el-table-column prop="remark" label="备注"></el-table-column>
        <el-table-column label="操作" width="256" align="center" fixed="right">
          <template slot-scope="scope">
            <el-row>
              <el-button v-has="permissionSetMainBusiness" v-if="scope.row.levels != 1" type="success" size="mini" plain @click="handleSetMainBusiness(scope.row)"> 设置主商户 </el-button>
              <el-button v-has="permissionDistributeBusiness" v-if="scope.row.levels != 1" type="primary" size="mini" plain @click="handleDistributeBusiness(scope.row)"> 分配商户 </el-button>
              <el-dropdown trigger="click" size="small">
                <el-button type="primary"><i class="fa fa-list-ul"></i>更多</el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-has="permissionEdit" @click.native="handleClickEditor(scope.row)">编辑</el-dropdown-item>
                  <!-- <el-dropdown-item v-has="permissionEdit" @click.native="handleSetMainBusiness(scope.row)"></el-dropdown-item> -->
                  <el-dropdown-item v-has="permissionDelete" @click.native="handleClickDelete(scope.row)">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <!-- <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page.pageNo" :page-sizes="[5, 10, 20, 30]" :page-size="page.pageSize" layout="total, sizes, jumper, next, pager, prev" :total="page.pageTotal"></el-pagination> -->
      <el-dialog :visible.sync="mainBusiness.show" title="设置主商户" center width="fit-content">
        <div class="dialog-content">
          <div class="item">
            <div class="label">设置主商户：</div>
            <el-select class="value" v-model="mainBusiness.businessId" clearable filterable placeholder="请选择商户">
              <el-option v-for="item in businessList" :value="item.id" :label="item.name" :key="item.id"> </el-option>
            </el-select>
          </div>
          <div class="item">
            <div class="label">商户自留比例：</div>
            <el-input class="value" v-model="mainBusiness.discount" v-maxnum="{ obj: mainBusiness, key: 'discount', max: 100 }" placeholder="可输入1-100之间" clearable>
              <template slot="suffix"> % </template>
            </el-input>
          </div>
        </div>
        <div slot="footer">
          <el-button type="primary" @click="confirmSetMainBuisness"> 确定 </el-button>
          <el-button @click="mainBusiness.show = false"> 取消 </el-button>
        </div>
      </el-dialog>
    </el-row>
  </div>
</template>
<script>
import * as message from '@/constants/message';
import DepartApi from '@/api/system/depart';
import BusinessApi from '@/api/business/business';
export default {
  name: 'DepartManagement',
  inject: ['reload'], //注入局部刷新
  data() {
    return {
      searchForm: {
        departName: '',
        departId: '',
      },
      departs: [],
      tableList: [],
      // page: {
      //   pageNo: 1,
      //   pageSize: 20,
      //   pageTotal: 0
      // },
      permissionAdd: 'SYSTEM_MANAGER_SYS_DEPART_LIST_ADD',
      permissionEdit: 'SYSTEM_MANAGER_SYS_DEPART_LIST_EDIT',
      permissionDelete: 'SYSTEM_MANAGER_SYS_DEPART_LIST_DELETE',
      permissionDistributeBusiness: 'SYSTEM_MANAGER_SYS_DEPART_LIST_DISTRIBUTE_BUSINESS',
      permissionSetMainBusiness: 'SYSTEM_MANAGER_SYS_DEPART_LIST_SET_MAIN_BUSINESS',
      mainBusiness: {
        show: false,
        discount: '',
        businessId: '',
      },
      rowItem: null,
      businessList: [],
    };
  },
  mounted() {
    this.init();
    window.addEventListener('keydown', this.keyDown);
  },
  activated() {
    if (this.$route.meta.keepAlive) {
      this.listTable();
    }
    if (this.$route.params.departId) {
      let departItem = this.tableList.filter((item) => {
        return item.departId == this.$route.params.departId;
      });
      let index = this.tableList.indexOf(departItem[0]);
      for (let item in this.tableList[index]) {
        if (this.$route.params[item]) {
          this.tableList[index][item] = this.$route.params[item];
        }
      }
    }
  },
  destroyed() {
    window.removeEventListener('keydown', this.keyDown, false);
  },
  watch: {
    //to去哪，from从哪来
    $route(to, from) {
      if (from.path == '/sys/departAdd' || from.path == '/sys/departEdit') {
        this.listTable();
      }
    },
  },
  methods: {
    init() {
      this.listTable();
      this.getDeparts();
    },
    keyDown(e) {
      //如果是回车则执行查询方法
      if (e.keyCode == 13) {
        this.onSearch();
      }
    },

    // 获取所有的公司
    getDeparts() {
      DepartApi.listDepart().then((res) => {
        this.departs = res.data;
      });
    },

    // 设置商户主用户
    handleSetMainBusiness(row) {
      this.rowItem = row;
      const { mainBusiness } = this;
      DepartApi.getMainBusiness({ sysDepartId: row.departId }).then((res) => {
        const { data } = res;
        mainBusiness.businessId = data ? data.businessId : '';
        mainBusiness.discount = data ? data.discount : '';
        mainBusiness.show = true;
      });

      BusinessApi.listIdNameVo({ sysDepartId: -row.departId }).then((res) => {
        const { data } = res;
        this.businessList = data;
        // dataForm.businessIds = data.filter(item => item.state).map(item => item.id)
      });
    },
    confirmSetMainBuisness() {
      const { mainBusiness, rowItem } = this;
      const { businessId, discount } = mainBusiness;
      if (!businessId) {
        this.$message.error('请选择商户');
        return;
      }
      this.$confirm('确定设置吗？', '提示', {}).then(() => {
        const params = {
          businessId,
          discount,
          sysDepartId: rowItem.departId,
        };
        DepartApi.setMainBusiness(params).then((params) => {
          this.$Utils.notifySuccess('设置成功');
          mainBusiness.show = false;
        });
      });
    },
    // 分配商户
    handleDistributeBusiness(row) {
      this.$router.push({
        path: '/business/distributeBusiness',
        query: {
          id: row.departId,
        },
      });
    },
    listTable() {
      let data = {
        departName: this.searchForm.departName,
        departId: this.searchForm.departId,
      };
      this.fetchData(data);
    },
    handleClickAdd() {
      this.$router.push({ path: '/sys/departAdd' });
    },
    handleClickEditor(row) {
      this.$router.push({ path: '/sys/departEdit', query: { id: row.departId } });
    },
    handleClickDelete(row) {
      this.$confirm(message.MSG_CONFIRM_DELETE, message.TITLE_PROMPT, {}).then(() => {
        DepartApi.deleteDepart({ departId: row.departId }).then((res) => {
          this.listTable();
          this.$Utils.notifySuccess();
        });
      });
    },
    onSearch() {
      this.listTable();
    },
    resetForm() {
      this.$refs.searchForm.resetFields();
      this.listTable();
    },
    fetchData(data) {
      DepartApi.listDeparts(data)
        .then((res) => {
          this.tableList = res.data;
        })
        .catch((error) => {});
    },
  },
};
</script>
<style lang="scss">
@import '@/assets/css/views/content.scss';
</style>

<style lang="scss"></style>
